import { app, shell, BrowserWindow, ipcMain, Tray, Menu } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

import path from 'path'
import { createStaticServer } from './httpService.js'

// 单实例锁定
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  // 创建静态文件服务器 - 支持多个路径映射
  const pathMappings = {
    '/': path.join(__dirname, '../../public/dist'), // 默认路径
    '/hfd68': path.join(__dirname, '../../public/hfd68'), // hfd68目录
    '/hfd87': path.join(__dirname, '../../public/hfd87'), // hfd87目录
    '/ry': path.join(__dirname, '../../public/ry'), // ry目录
    '/yjs': path.join(__dirname, '../../public/yjs'), // yjs目录
    '/ydx': path.join(__dirname, '../../public/ydx'), // ydx目录
    '/pq': path.join(__dirname, '../../public/pq'), // pq目录
    '/by': path.join(__dirname, '../../public/by'), // by目录
    '/dk': path.join(__dirname, '../../public/dk'), // dk目录
  }
  
  let httpService = null
  let isServerRunning = false

  // 启动服务器的函数
  async function startHttpServer() {
    if (!isServerRunning) {
      try {
        httpService = createStaticServer(pathMappings, 8888)
        await httpService.start()
        isServerRunning = true
        console.log('HTTP server started successfully')
      } catch (error) {
        console.error('Failed to start HTTP server:', error)
      }
    }
  }

  // 停止服务器的函数
  async function stopHttpServer() {
    if (isServerRunning && httpService) {
      try {
        await httpService.stop()
        isServerRunning = false
        httpService = null
        console.log('HTTP server stopped')
      } catch (error) {
        console.error('Failed to stop HTTP server:', error)
      }
    }
  }

  let mainWindow = null
  let tray = null

  // 当有第二个实例尝试启动时，聚焦到主窗口
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      if (!mainWindow.isVisible()) mainWindow.show()
      mainWindow.focus()
    }
  })

  function createWindow() {
    // Create the browser window.
    const { screen } = require('electron')
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width, height } = primaryDisplay.workAreaSize
    
    mainWindow = new BrowserWindow({
      width: Math.floor(width * 0.8) || 1300,
      height: Math.floor(height * 0.8) || 800,
      show: false,
      autoHideMenuBar: true,
      frame: false,
      ...(process.platform === 'linux' ? { icon } : {}),
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false,
        nodeIntegration: true,
        contextIsolation: false,
        experimentalFeatures: true,
        enableBlinkFeatures: 'WebHID,WebSerial,WebUSB,WebBluetooth',
        webSecurity: false,
        webviewTag: true
      }
    })

    mainWindow.on('ready-to-show', () => {
      mainWindow.show()
      // 只在开发模式下自动打开DevTools
      if (is.dev) {
        mainWindow.webContents.openDevTools({ mode: 'detach' })
      }
    })

    mainWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    // 处理设备权限请求
    mainWindow.webContents.session.setPermissionRequestHandler(
      (webContents, permission, callback) => {
        const allowedPermissions = ['hid', 'serial', 'usb', 'bluetooth']

        if (allowedPermissions.includes(permission)) {
          callback(true)
        } else {
          callback(false)
        }
      }
    )

    // 处理设备选择对话框
    mainWindow.webContents.session.setDevicePermissionHandler(() => {
      return true // 允许所有设备访问
    })

    // 处理webview的权限请求
    mainWindow.webContents.on('did-attach-webview', (event, webContents) => {
      webContents.session.setPermissionRequestHandler((webContents, permission, callback) => {
        const allowedPermissions = ['hid', 'serial', 'usb', 'bluetooth']
        if (allowedPermissions.includes(permission)) {
          callback(true)
        } else {
          callback(false)
        }
      })
      
      webContents.session.setDevicePermissionHandler(() => {
        return true
      })
    })

    // 阻止窗口关闭，改为隐藏到托盘
    mainWindow.on('close', (event) => {
      if (!app.isQuiting) {
        event.preventDefault()
        mainWindow.hide()
        // 在Windows上，隐藏到托盘时显示提示
        if (process.platform === 'win32' && tray) {
          tray.displayBalloon({
            title: 'HID 设备管理器',
            content: '应用已最小化到托盘，双击托盘图标可重新打开'
          })
        }
      }
    })

    // HMR for renderer base on electron-vite cli.
    // Load the remote URL for development or the local html file for production.
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
      // 打包后使用本地HTML文件
      mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
    }
  }

  // 创建托盘
  function createTray() {
    tray = new Tray(icon)
    
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示窗口',
        click: () => {
          if (mainWindow) {
            mainWindow.show()
            mainWindow.focus()
          }
        }
      },
      {
        label: '退出',
        click: () => {
          app.isQuiting = true
          app.quit()
        }
      }
    ])
    
    tray.setToolTip('HID 设备管理器')
    tray.setContextMenu(contextMenu)
    
    // 双击托盘图标显示窗口
    tray.on('double-click', () => {
      if (mainWindow) {
        if (mainWindow.isVisible()) {
          mainWindow.hide()
        } else {
          mainWindow.show()
          mainWindow.focus()
        }
      }
    })

    // 单击托盘图标显示窗口
    tray.on('click', () => {
      if (mainWindow) {
        if (mainWindow.isVisible()) {
          mainWindow.hide()
        } else {
          mainWindow.show()
          mainWindow.focus()
        }
      }
    })
  }

  // This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // 启动HTTP服务器
  await startHttpServer()

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  // 窗口控制IPC处理器
  ipcMain.on('window-minimize', () => {
    mainWindow.minimize()
  })

  ipcMain.on('window-maximize', () => {
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize()
    } else {
      mainWindow.maximize()
    }
  })

  ipcMain.on('window-close', () => {
    mainWindow.hide()
  })

  // 打开开发者工具
  ipcMain.on('open-dev-tools', () => {
    if (mainWindow) {
      mainWindow.webContents.openDevTools({ mode: 'detach' })
    }
  })

  createTray()
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

  // Quit when all windows are closed, except on macOS. There, it's common
  // for applications and their menu bar to stay active until the user quits
  // explicitly with Cmd + Q.
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      stopHttpServer().then(() => {
        app.quit()
      })
    }
  })

  // 应用退出前清理托盘和服务器
app.on('before-quit', async () => {
  app.isQuiting = true
  if (tray) {
    tray.destroy()
  }
  await stopHttpServer()
})

  // In this file you can include the rest of your app's specific main process
  // code. You can also put them in separate files and require them here.
}
